package com.cqc.service.impl;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch.core.IndexRequest;
import co.elastic.clients.elasticsearch.core.IndexResponse;
import com.cqc.pojo.Document;
import com.cqc.service.DocumentService;
import org.apache.tika.Tika;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service
public class DocumentServiceImpl implements DocumentService {

    private final ElasticsearchClient client;
    private final Tika tika = new Tika();

    @Autowired
    public DocumentServiceImpl(ElasticsearchClient client) {
        this.client = client;
    }

    @Override
    public String indexDocument(String id, MultipartFile file) throws Exception {
        // 使用Tika从文件中提取文本
        String content = tika.parseToString(file.getInputStream());

        // 创建文档对象
        Document document = new Document(id, file.getOriginalFilename(), content);

        // 创建Index请求
        IndexRequest<Document> request = new IndexRequest.Builder<Document>()
                .index("documents")
                .id(document.getFileId())
                .document(document)
                .build();

        // 执行索引操作并获取响应
        IndexResponse response = client.index(request);
        return "Indexed with version: " + response.version();
    }

    //public SearchResponse<Document> searchDocuments(String query) throws Exception {
    //    SearchRequest searchRequest = new SearchRequest.Builder()
    //            .index("documents")
    //            .query(q -> q.match(m -> m.field("content").query(query)))
    //            .build();
    //
    //    return client.search(searchRequest, Document.class);
    //}
}


